package com.ynny.controller;

import com.ynny.dao.UserDao;
import com.ynny.entity02.R;
import com.ynny.entity02.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping ("/user")
public class UserController {
    @Autowired
    private UserDao UserDao;


    //查询所有用户信息
    @RequestMapping("/list")
    public R list(){
        List<User> list = UserDao.selectAllUsers();
        return R.ok(list);
    }

    @RequestMapping("/{id}")
    public R deleteUser(@PathVariable("id") Integer id){
        int i = UserDao.deleteUser(id);
        return  R.ok(null);
    }

    @RequestMapping("/add")
    public R addUser( @RequestBody User user){
        int i = UserDao.addUser(user);
        if (i == 200 ){
            return R.ok(user.getUsername());
        } else if (i == 202) {
            return new R(202,"用户名已经存在",null);
        }
        return  R.ok(null);
    }


    @GetMapping("/{id}")
    public R get(@PathVariable(name = "id") Integer id){

        System.out.println("获取的id：" + id);

        User user = UserDao.selectUserById(id);
        if (user == null) {
            new R(201,"查询无果",null);
        }

        return R.ok(user);
    }

    @PutMapping
    public R update(@RequestBody User user){

        System.out.println("需要修改的用户为: " + user);

        int i = UserDao.updateUser(user);

        if (i > 0 ){
            return R.ok(user.getUsername());
        }

        return R.ok(null);

    }
}
